<template>
  <HeaderComponent />
  <div class="container">
    <div style="width: 80%; margin: 0 auto; display: flex; border: none">
      <!--左侧选择-->
      <div class="left-menu">
        <el-menu
          :default-active="activeIndex"
          mode="vertical"
          @select="handleSelect"
          style="background-color: #f5f7fa"
        >
          <el-menu-item index="personalInfo">个人资料</el-menu-item>
          <el-menu-item index="accountSettings">账号设置</el-menu-item>
        </el-menu>
      </div>
      <!--个人资料-->
      <div class="right-content">
        <!--顶部个人信息界面-->
        <div class="personalInfo">
          <div class="right-header">
            <img
              class="avatar"
              :src="userinfo.avatar || '/assets/avatar/default.jpg'"
              alt="Avatar"
              @click="handleAvatarClick"
            />
            <input
              type="file"
              id="imageInput"
              accept="image/*"
              ref="imageInput"
              style="display: none"
            />
            <div class="user-info">
              <span class="username">{{ userinfo.username }}</span>
            </div>
          </div>
          <div class="main-info">
            <span class="main-msg">基本信息</span>
            <div class="main-content">
              <el-row>
                <el-col :span="8">手机号</el-col>
                <el-col :span="16"><input disabled v-model="userinfo.phone" /></el-col>
              </el-row>
              <el-row>
                <el-col :span="8">用户昵称</el-col>
                <el-col :span="16"><input v-model="userinfo.username" /></el-col>
              </el-row>
              <el-row>
                <el-col :span="8">性别</el-col>
                <el-col :span="16">
                  <el-select v-model="userinfo.sex" placeholder="请选择性别">
                    <el-option label="男" value="男" />
                    <el-option label="女" value="女" />
                  </el-select>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">个人简介</el-col>
                <el-col :span="16"><input v-model="userinfo.sign" /></el-col>
              </el-row>
              <el-row>
                <el-col :span="8">所在地区</el-col>
                <el-col :span="16">
                  <!-- 地区选择器 -->
                  <el-select v-model="userinfo.from" placeholder="请选择所在地区">
                    <el-option label="北京" value="北京" />
                    <el-option label="上海" value="上海" />
                    <el-option label="广州" value="广州" />
                    <el-option label="深圳" value="深圳" />
                    <!-- 可根据需求添加更多地区选项 -->
                  </el-select>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">出生日期</el-col>
                <el-col :span="16">
                  <!-- 日期选择器 -->
                  <el-date-picker
                    v-model="userinfo.born"
                    type="date"
                    placeholder="选择出生日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                  />
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8"></el-col>
                <el-col :span="16">
                  <el-button type="primary" @click="submit">修改个人信息</el-button>
                </el-col>
              </el-row>
            </div>
          </div>
        </div>
        <!--账号设置-->
        <div class="accountSettings">
          <div class="main-info">
            <span class="main-msg">账号设置</span>
            <div class="main-content psd">
              <el-row>
                <el-col :span="8">请输入原密码</el-col>
                <el-col :span="16"
                  ><input v-model="oldpassword" type="password"
                /></el-col>
              </el-row>
              <el-row>
                <el-col :span="8">请输入密码</el-col>
                <el-col :span="16"><input v-model="password" type="password" /></el-col>
              </el-row>
              <el-row>
                <el-col :span="8">请确认密码</el-col>
                <el-col :span="16"><input v-model="repassword" type="password" /></el-col>
              </el-row>
              <el-row>
                <el-col :span="8"></el-col>
                <el-col :span="16">
                  <el-button type="primary" @click="submitpsd">修改密码</el-button>
                </el-col>
              </el-row>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import HeaderComponent from "../../components/HeaderComponent.vue";
import userStore from "../../store/index";
import api from "../../utils/index.js"; 
import { useRouter, useRoute } from "vue-router";

const router = useRouter();
const userStoreInfo = userStore();
const user = userStoreInfo.getUser();
const userinfo = reactive({});
const oldpassword = ref("");
const password = ref("");
const repassword = ref("");
const activeIndex = ref("personalInfo");

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const response = await api.get(`/users?id=${user.id}`);
    Object.assign(userinfo, response.data[0]);
  } catch (error) {
    ElMessage.error("获取用户信息失败: " + error.message);
  }
};

// 处理菜单选择
const handleSelect = (index) => {
  activeIndex.value = index;
  document.querySelector(".personalInfo").style.display =
    index === "personalInfo" ? "block" : "none";
  document.querySelector(".accountSettings").style.display =
    index === "accountSettings" ? "block" : "none";
};

// 提交个人信息修改
const submit = async () => {
  try {
    await api.put(`/users/${userinfo.id}`, userinfo);
    ElMessage.success("修改成功！");
  } catch (error) {
    ElMessage.error("修改失败！");
  }
};

// 提交密码修改
const submitpsd = async () => {
  // 新增原密码验证
  if (!oldpassword.value) {
    ElMessage.error("请输入原密码！");
    return;
  }
  if (!password.value || !repassword.value) {
    ElMessage.error("请输入新密码和确认密码！");
    return;
  }
  if (password.value !== repassword.value) {
    ElMessage.error("两次输入的新密码不一致！");
    return;
  }
  // 新增原密码验证请求
  const verifyResponse = await api.get(`/users/${userinfo.id}`, {});
  if (verifyResponse.data.password != oldpassword.value) {
    ElMessage.error("原密码输入错误");
    return;
  } else {
    await api.patch(`/users/${userinfo.id}`, {
      password: password.value,
    });
    ElMessage.success("密码修改成功！");
    userStoreInfo.clearUser();
    router.push("/login");
  }
};

// 处理头像点击事件
const imageInput = ref(null);
const handleAvatarClick = () => {
  if (imageInput.value) {
    imageInput.value.click();
  }
};

// 处理头像文件变更
const handleFileChange = () => {
  const file = imageInput.value.files[0];
  const reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = async () => {
    const base64Image = reader.result;
    await api.patch(`/users/${userinfo.id}`, {
      avatar: base64Image,
    });
    ElMessage.success("头像修改成功！");
    fetchUserInfo();
  };
};

// 组件挂载时初始化
onMounted(() => {
  fetchUserInfo();
  // 绑定头像上传事件
  if (imageInput.value) {
    imageInput.value.addEventListener("change", handleFileChange);
  }
});
</script>
<style scoped>
.container {
  width: 100%;
  min-height: 100vh;
  background-color: #f8f9fa;
  padding: 24px;
}

.left-menu {
  width: 240px;
  background-color: #fff;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  margin-right: 24px;
  border-radius: 12px;
}

.el-menu {
  border-right: none;
}

.el-menu-item {
  background-color: #fff;
  height: 48px;
  line-height: 48px;
  font-size: 14px;
  color: #606266;
  transition: all 0.2s ease;
}
.el-menu-item:first-child {
  border-top-left-radius: 12px;
  border-top-right-radius: 12px;
}
.el-menu-item:hover {
  background-color: #f5f7fa;
  color: #409eff;
}

.right-content {
  flex: 1;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  padding: 24px;
}

.right-header {
  display: flex;
  align-items: center;
  padding: 24px;
  background-color: #f8f9fa;
  border-radius: 12px;
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  margin-right: 20px;
  border: 4px solid #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.username {
  font-size: 24px;
  font-weight: 600;
  color: #1c1e21;
}

.main-info {
  padding: 24px;
}

.main-msg {
  font-size: 18px;
  font-weight: 600;
  color: #1c1e21;
  margin-bottom: 24px;
  padding-bottom: 5px;
  display: block;
  border-bottom: 1px solid #e4e7ed;
}

.el-row {
  margin-bottom: 24px;
  align-items: center;
}

.el-col {
  font-size: 14px;
  color: #606266;
}

input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  font-size: 14px;
  color: #1c1e21;
  transition: border-color 0.2s ease;
}

input:focus {
  outline: none;
  border-color: #409eff;
}

.el-button {
  width: 100%;
  padding: 12px;
  font-size: 14px;
  border-radius: 6px;
  transition: all 0.2s ease;
}

.el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
}

.el-button--primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.accountSettings {
  display: none;
}
</style>
